﻿//==================================================================
// Copyright (C) 2015 福流网络
// 作 者：江怀玉
// 日 期：2015-04-22
// 描 述：页面操作
//        
// 版 本：1.00
// 修改历史纪录
// 版 本  修改时间      修改人       修改内容
// 1.00   2015/4/22     江怀玉           
//==================================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using FL.DBModule.Sys;
using FL.Web.BackEnd;
using FL.Common;
using FL.Bussiness;
using FL.DBModule;
using FL.DataImport;
using System.Text;
using System.Data;

using System.Collections;
using System.Data.SqlClient;


namespace FL.Web.BackEnd
{
    public partial class DataAction : BasePage 
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string action = this.GetStringFromQueryString("action", "");
            string entity = this.GetStringFromQueryString("entity", "");
            string paraCondtion = this.GetStringFromQueryString("paraCondtion", "");
            switch (entity)
            {


                #region 部门数据权限
                
                #endregion
                default:
                    switch (action)
                    {
                        case "dept":
                            FL.Bussiness.Sys.BUser user = new Bussiness.Sys.BUser();
                            string jsonData = user.GetUserFunctionDataDeptInfo(this.UserId, this.FunctionID, paraCondtion);
                            Response.Write(jsonData.ToString());
                            Response.End();
                            break;    
                        //break;
                        case "runProc":
                            if (entity == "proc")
                            {
                                string procName = this.GetStringFromQueryString("procName", "");
                                string parameters = this.GetStringFromQueryString("parameters", "");
                                if (parameters == "")
                                {
                                    parameters = Request["parameters"];
                                }
                                RunPrc(procName, parameters);
                            }
                            if (entity == "proc2")
                            {
                                string procName = this.GetStringFromQueryString("procName", "");
                                string parameters = this.GetStringFromQueryString("parameters", "");
                                RunPrc2(procName, parameters);
                            }
                            break;

                        case "runSpHelp":
                            DataTable dt = this._bll.GetDataBySqlComm("sp_helptext " + this.GetStringFromQueryString("object", ""));
                                           
                            if (dt == null) { return; }
                            StringBuilder sb = new StringBuilder("");
                            foreach (DataRow row in dt.Rows)
                            {
                                sb.AppendLine(row.ItemArray[0].ToString());
                            }
                            Response.Write(sb.ToString());
                           
                            break;

                        case "CommonDataImport":
                            string tableName = this.GetStringFromQueryString("table", "");
                            string fileName = this.GetStringFromQueryString("file", "");
                            string filePath = Server.MapPath("/") + "Upload/" + fileName;
                            DataImportBase dib = new DataImportBase();
                            DataTable dt1 = dib.GetExeclTable(filePath);
                            try
                            {
                                dib.Import(dt1, tableName);
                                Response.Write("importSucess");
                            }
                            catch(Exception ex){
                                throw new ErrorException(ex,this.User);
                            }
                            break;
                        case "initScript":
                            string[] files = System.IO.Directory.GetFiles(Server.MapPath("/Scripts/AppJs/"));
                            foreach (string _file in files)
                            {
                                DataTableBaseEntity _entity = new DataTableBaseEntity();
                                _entity.TableName = "Set_Script";
                                _entity.CreateDT();
                                _entity.DRow[_entity.getKey()] = Guid.NewGuid();
                                _entity.DRow["FunctionID"] = DBNull.Value;
                                _entity.DRow["EntityName"] = "";
                                _entity.DRow["FileName"] = "/Scripts/AppJs/" + FileHelper.GetFileNameNoPath(_file);
                                _entity.DRow["FilePath"] = FileHelper.GetFileNameNoPath(_file); ;
                                _entity.DRow["add_user"] = this.UserId;
                                _entity.DRow["add_time"] = System.DateTime.Now;
                                _entity.DRow["ScriptText"] = FileHelper.GetFileContent(_file);
                                _entity.KeyField = _entity.GetKey()[0];
                                this._bll.entity = _entity;
                                this._bll.Insert();
                            }
                            break;
                        case "getSequence":
                            string para = GetStringFromQueryString("para", "");
                            string[] _para = para.Split(',');
                            string code = "";
                            if (_para.Length == 1)
                            {
                                code = FL.Bussiness.IDMaker.GetSequenceStr(_para[0]);
                            }
                            if (_para.Length == 2)
                            {
                                code = FL.Bussiness.IDMaker.GetSequenceStr(_para[0], _para[1]);
                            }
                            if (_para.Length == 3)
                            {
                                code = FL.Bussiness.IDMaker.GetSequenceStr(_para[0], _para[1], _para[2]);
                            }
                            if (_para.Length == 4)
                            {
                                code = FL.Bussiness.IDMaker.GetSequenceStr(_para[0], _para[1], _para[2], _para[3]);
                            }
                            Response.Write(code);
                            Response.End();
                            break;
                       
                        default:
                            break;
                    }
                    break;

            }         
            
        }
        private void BuildReportFile(string fileContext, string fileName)
        {

           
            if (fileContext != "" && fileName != "")
            {
                Response.Clear();
                Response.Write(fileContext);
                Response.Buffer = true;
                Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName + ".xml");
                Response.ContentEncoding = System.Text.Encoding.UTF8;
                Response.ContentType = "application/vnd.ms-xml";
                this.EnableViewState = false;
            }
        }

        #region 权限相关操作
        /// <summary>
        /// 设置用户角色
        /// </summary>
        void SetUserRoles()
        {
            string[] roles = this.GetStringFromQueryString("roles", "").Split(',');
            Guid? userID = GetGuidFromQueryString("userid");
            foreach (var roleid in roles)
            {
                DataTableBaseEntity entity = new DataTableBaseEntity();
                entity.TableName = "SysUserRole";
                entity.CreateDT();
                entity.DRow[entity.getKey()] = Guid.NewGuid();
                entity.DRow["UserID"] = userID;
                entity.DRow["RoleID"] = new Guid(roleid);
                entity.DRow["Remark"] = "";
                entity.KeyField = entity.GetKey()[0];
                this._bll.entity = entity;
                try
                {
                    this._bll.Insert(entity);
                }
                catch (Exception e)
                {
                    HttpContext.Current.Response.Write(e.Message);
                }
            }
            HttpContext.Current.Response.Write("1");
        }

        /// <summary>
        /// 设置角色用户
        /// </summary>
        void SetRoleUsers()
        {
            string[] users = this.GetStringFromQueryString("users", "").Split(',');
            Guid? roleid = GetGuidFromQueryString("roleid");
            foreach (var userid in users)
            {
                DataTableBaseEntity entity = new DataTableBaseEntity();
                entity.TableName = "SysUserRole";
                entity.CreateDT();
                entity.DRow[entity.getKey()] = Guid.NewGuid();
                entity.DRow["UserID"] = new Guid(userid);;
                entity.DRow["RoleID"] = roleid;
                entity.DRow["Remark"] = "";
                entity.KeyField = entity.GetKey()[0];
                this._bll.entity = entity;
                try
                {
                    this._bll.Insert(entity);
                }
                catch (Exception e)
                {
                    HttpContext.Current.Response.Write(e.Message);
                }
                //entity.EntityJson = FL.Common.Globals.DataRowToJSON(((DataTableBaseEntity)entity).DRow);
                //HttpContext.Current.Response.Write(entity.EntityJson.Replace("\\\\\"", "\\\"").Replace("\\", "\\\\"));
            }
            HttpContext.Current.Response.Write("1");
        }

        /// <summary>
        /// 设置角色岗位
        /// </summary>
        void SetRolePosts()
        {
            string[] posts = this.GetStringFromQueryString("posts", "").Split(',');
            Guid? roleid = GetGuidFromQueryString("roleid");
            foreach (var postid in posts)
            {
                DataTableBaseEntity entity = new DataTableBaseEntity();
                entity.TableName = "SysPostRole";
                entity.CreateDT();
                entity.DRow[entity.getKey()] = Guid.NewGuid();
                entity.DRow["RoleID"] = roleid;
                entity.DRow["PostID"] = new Guid(postid);
                entity.DRow["Remark"] = "";
                entity.KeyField = entity.GetKey()[0];
                this._bll.entity = entity;
                try
                {
                    this._bll.Insert(entity);
                }
                catch (Exception e)
                {
                    HttpContext.Current.Response.Write(e.Message);
                }
                //entity.EntityJson = FL.Common.Globals.DataRowToJSON(((DataTableBaseEntity)entity).DRow);
                //HttpContext.Current.Response.Write(entity.EntityJson.Replace("\\\\\"", "\\\"").Replace("\\", "\\\\"));
            }
            HttpContext.Current.Response.Write("1");
        }


        /// <summary>
        /// 设置岗位角色
        /// </summary>
        void SetPostRoles()
        {
            string[] roles = this.GetStringFromQueryString("roles", "").Split(',');
            Guid? postid = GetGuidFromQueryString("postid");
            foreach (var roleid in roles)
            {
                DataTableBaseEntity entity = new DataTableBaseEntity();
                entity.TableName = "SysPostRole";
                entity.CreateDT();
                entity.DRow[entity.getKey()] = Guid.NewGuid();
                entity.DRow["PostID"] = postid;
                entity.DRow["RoleID"] = new Guid(roleid);
                entity.DRow["Remark"] = "";
                entity.KeyField = entity.GetKey()[0];
                this._bll.entity = entity;
                try
                {
                    this._bll.Insert(entity);
                }
                catch (Exception e)
                {
                    HttpContext.Current.Response.Write(e.Message);
                }
            }
            HttpContext.Current.Response.Write("1");
        }
        #endregion
        
        #region 执行存储过程
        void RunPrc(string procName, string parameters)
        {
            string[] s1 = { "[@@@]" };
            object[] para = parameters.Split(',');
            try
            {
                var result = this._bll.RunProcedure(procName, para);
                //_bll.GetDataBySqlComm("exec spName '',''");
                //result.Rows
               // result.GetRow(0)
                //if(result.
                var returnValue = "";
                if (result.Rows > 0)
                {
                    returnValue = result.GetRow(0)[0].ToString();
                }
                if (result.Rows == 0)
                {
                    Response.Write("{stuats:1,msg:'" + result.Rows.ToString() + "'}");
                }
                else
                {
                    Response.Write("{stuats:1,msg:'" + result.Rows.ToString() + "',returnValue:'" + returnValue + "'}");
                }
                
            }
            catch (Exception exp)
            {
                Response.Write("{stuats:0,msg:'"+exp.Message+"'}");
            }
        }


        /// <summary>
        /// 单字段数据保存
        /// </summary>
        /// <param name="table">表名</param>
        /// <param name="field">字段名</param>
        /// <param name="json">ID</param>
        /// <param name="value">值</param>
        public void UpdateSingleFieldAction(string table, string field, string json, string value)
        {
            string ids = json;
            if (string.IsNullOrEmpty(ids))
            {
                ids = GetStringFromQueryString("id", "");
            }
            DataTableBaseEntity instance = new DataTableBaseEntity();
            instance.TableName = table;
            //instance.SetConn();
            string[] strArrary = instance.GetKey();
            if (strArrary != null)
            {
                instance.KeyField = strArrary[0];
                instance.KeyFieldDataType = strArrary[1];
            }
            string[] _ids = json.Split(',');
            string updateSql = "update {0} set {1}='{2}' where {3}='{4}'";
            StringBuilder SqlComm = new StringBuilder("");
            try
            {
                foreach (string id in _ids)
                {
                    SqlComm.AppendLine(string.Format(updateSql, table, field, instance.KeyField, value));
                }
                _bll.entity = instance;
                _bll.RunSqlCommand(SqlComm.ToString());
                FLContext.Response.Write("1");
            }
            catch (Exception e)
            {
                FLContext.Response.Write(e.Message);
            }
        }


        /// <summary>
        /// 执行存储过程，并返回结果集
        /// </summary>
        /// <param name="procName"></param>
        /// <param name="parameters"></param>
        void RunPrc2(string procName, string parameters)
        {
            object[] para = parameters.Split(',');
            try
            {
                string _para = string.Empty;
                foreach (object p in para)
                {
                    if (_para.Length == 0)
                    {
                        _para = _para + "'" + p.ToString() + "'";
                    }
                    else
                    {
                        _para = _para + ",'" + p.ToString() + "'";
                    }
                }
                DataTable result = _bll.GetDataBySqlComm(string.Format("exec {0} {1}",procName,_para));
                string resultJson = FL.Common.Globals.DataTableToJSON(result);
                Response.Write(resultJson);
            }
            catch (Exception exp)
            {
                Response.Write("{stuats:0,msg:'" + exp.Message + "'}");
            }
        }
        #endregion

    }

    class Post
    {
        public Guid DutyID
        {
            get;
            set;
        }

        public Guid DeptID
        {
            get;
            set;
        }
    }

}